import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router/index'
import { store } from '../store'
import config from '~/config'

// 创建 axios 实例
const instance = axios.create({
    baseURL: config[import.meta.env.MODE].baseUrl ,
    timeout: 30000,
    headers: {'Content-Type': 'application/x-www-form-urlencoded','req_terminal':'web','vn':'1.1','svn':'1.0.0','lau':'zh_CN','nw':'4G'} 
})

// 从localStorage中获取tokenobj，tokenobj存的是object信息，有access_token和 refresh_token和 expires_in,两个字段

instance.interceptors.request.use((config) => {//请求拦截器
  const token = store.getters.token;
  const expries=store.getters.expries;
  let timer;
  clearTimeout(timer);
  // 添加请求头
  config.headers['Authorization'] =`Bearer ${token}`;
  // 登录接口和刷新token接口绕过
  if (config.url.indexOf('/oauth/token') >= 0) {
    return config
  }
  if (token && expries) {
    const now = Date.now()//都是获取1970年1月1日截止到现在时刻的时间戳，但是从性能上来讲 Date.now()要快于new.Date().getTime()可以从代码执行上来看
    // console.log(now,tokenObj.expires_in)
    if (now >= expries) {//已经过期了
      ElMessage.error('token已过期,请重新登录');
      timer=setTimeout(()=>{
        router.push({ path: '/login' })
      },1500)
    }
  }
  return config
}, (error) => {
  // Do something with request error
  return Promise.reject(error)
})


export default instance